package com.sangfor.ssl.service.netmonitor;

import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.NetworkInfo;
import android.text.TextUtils;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.service.line.LineResult;
import com.sangfor.ssl.service.netmonitor.NetworkCacheInfo;
import com.sangfor.ssl.service.utils.IGeneral;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;

/* loaded from: classes2.dex */
public class NetworkMonitor {
    private static final long CACHE_VALID_PERIOD = 86400000;
    private static final String PREFERENCE_NAME = "com.network.prefs";
    private static final String PROTO_HTTPS_HEAD = "https://";
    private static final String PROTO_HTTP_HEAD = "http://";
    private static final String TAG = "NetworkMonitor";
    private static final String kEY_NETWORK_CACHE_INFO = "key.NETWORK_CACHE_INFO";
    private Context mAppContext;
    private NetworkMonitorReceiver mNetworkMonitorReceiver;

    /* loaded from: classes2.dex */
    public interface NetworkListener {
        void onNetworkChanged(NetworkInfo networkInfo, boolean z);
    }

    /* loaded from: classes2.dex */
    public interface WiFiStateListener {
        void onWiFiChanged(int i, int i2);
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public static class SingletonHolder {
        private static final NetworkMonitor INSTANCE = new NetworkMonitor();

        private SingletonHolder() {
        }
    }

    public static final NetworkMonitor getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private NetworkMonitor() {
        this.mNetworkMonitorReceiver = null;
    }

    public void startMonitor(Context context) {
        this.mAppContext = context.getApplicationContext();
        if (this.mNetworkMonitorReceiver == null) {
            this.mNetworkMonitorReceiver = new NetworkMonitorReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
            this.mAppContext.registerReceiver(this.mNetworkMonitorReceiver, intentFilter);
        }
    }

    public void stopMonitor(Context context) {
        Context applicationContext = context.getApplicationContext();
        this.mAppContext = applicationContext;
        NetworkMonitorReceiver networkMonitorReceiver = this.mNetworkMonitorReceiver;
        if (networkMonitorReceiver != null) {
            applicationContext.unregisterReceiver(networkMonitorReceiver);
            this.mNetworkMonitorReceiver = null;
        }
    }

    private boolean isAppContextValid() {
        if (this.mAppContext == null) {
            Log.debug(TAG, "App Context is invalid.");
            return false;
        }
        return true;
    }

    public void registerNetworkMonitor(NetworkListener networkListener) {
        if (networkListener == null) {
            Log.error(TAG, "Register network monitor fail, NetworkListener is null");
        } else {
            this.mNetworkMonitorReceiver.registerNetworkMonitorListener(networkListener);
        }
    }

    public void unRegisterNetworkMonitor(NetworkListener networkListener) {
        if (networkListener == null) {
            Log.error(TAG, "Unregister network monitor fail, NetworkListener is null");
        } else {
            this.mNetworkMonitorReceiver.unRegisterNetworkMonitorListener(networkListener);
        }
    }

    public void registerWiFiStateListener(WiFiStateListener wiFiStateListener) {
        if (wiFiStateListener == null) {
            Log.error(TAG, "Register wifi change listener fail, WiFiStateListener is null");
        } else {
            this.mNetworkMonitorReceiver.registerWiFiStateListener(wiFiStateListener);
        }
    }

    public void unRegisterWiFiStateListener(WiFiStateListener wiFiStateListener) {
        if (wiFiStateListener == null) {
            Log.error(TAG, "Unregister wifi change listener fail, WiFiStateListener is null");
        } else {
            this.mNetworkMonitorReceiver.unRegisterWiFiStateListener(wiFiStateListener);
        }
    }

    private void updateCacheNetworkInfo(String str) {
        putStringValue(kEY_NETWORK_CACHE_INFO, str);
    }

    private String getCacheNetworkInfo() {
        return getStringValue(kEY_NETWORK_CACHE_INFO);
    }

    protected String getCacheNetworkInfo(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        if (i != 0) {
            return i != 1 ? "" : JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), NetworkCacheInfo.KEY_INFO, "");
        }
        return JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), NetworkCacheInfo.KEY_INFO, "");
    }

    public String getCacheHostInfo() {
        return JsonUtils.getString(getCacheNetworkInfo(), NetworkCacheInfo.KEY_HOST, "");
    }

    public void updateCacheNetworkInfo(String str, LineResult lineResult, NetworkBean networkBean) {
        if (TextUtils.isEmpty(str) || lineResult == null || networkBean == null) {
            Log.error(TAG, "select result is error");
            return;
        }
        NetworkCacheInfo fromJson = fromJson(getCacheNetworkInfo());
        String hostFromUrl = getHostFromUrl(str);
        int portFromUrl = getPortFromUrl(str);
        if (portFromUrl != -1) {
            fromJson.setHost(String.format(Locale.getDefault(), "%s:%s", hostFromUrl, Integer.valueOf(portFromUrl)));
        } else {
            fromJson.setHost(hostFromUrl);
        }
        String format = String.format(Locale.getDefault(), "%s;%s", lineResult.selectUrl, lineResult.vpnAddress);
        String valueOf = String.valueOf(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();
        String[] strArr = lineResult.candidate;
        for (int i = 0; i < strArr.length; i++) {
            if (i < strArr.length - 1) {
                sb.append(strArr[i]);
                sb.append(";");
            } else {
                sb.append(strArr[i]);
            }
        }
        Log.info(TAG, "Candidates:" + Arrays.toString(strArr));
        NetworkCacheInfo.InfoBlock infoBlock = new NetworkCacheInfo.InfoBlock(format, networkBean.networkInfo, sb.toString(), valueOf);
        if (1 == networkBean.networkType) {
            fromJson.setWifiInfo(infoBlock);
        } else if (networkBean.networkType == 0) {
            fromJson.setMobileInfo(infoBlock);
        } else {
            Log.error(TAG, "Wrong network type!");
            return;
        }
        Log.info(TAG, "Update New cache json:" + toJson(fromJson));
        updateCacheNetworkInfo(toJson(fromJson));
    }

    public String getCacheSelectLine(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        if (i == 0) {
            String string = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), "Line", "");
            if (TextUtils.isEmpty(string)) {
                return "";
            }
            String[] split = string.split(";");
            return split.length > 1 ? split[0] : "";
        } else if (1 == i) {
            String string2 = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), "Line", "");
            if (TextUtils.isEmpty(string2)) {
                return "";
            }
            String[] split2 = string2.split(";");
            return split2.length > 1 ? split2[0] : "";
        } else {
            return "";
        }
    }

    public String[] getCacheSelectLineWithAddress(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        if (i == 0) {
            String string = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), "Line", "");
            if (!TextUtils.isEmpty(string)) {
                String[] split = string.split(";");
                return split.length > 1 ? split : new String[0];
            }
        } else if (1 == i) {
            String string2 = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), "Line", "");
            if (!TextUtils.isEmpty(string2)) {
                String[] split2 = string2.split(";");
                return split2.length > 1 ? split2 : new String[0];
            }
        }
        return new String[0];
    }

    public String[] getCacheCandidates(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        if (i == 0) {
            String string = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), NetworkCacheInfo.KEY_CANDIDATE, "");
            if (!TextUtils.isEmpty(string)) {
                String[] split = string.split(";");
                return split.length > 0 ? split : new String[0];
            }
        } else if (1 == i) {
            String string2 = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), NetworkCacheInfo.KEY_CANDIDATE, "");
            if (!TextUtils.isEmpty(string2)) {
                String[] split2 = string2.split(";");
                return split2.length > 0 ? split2 : new String[0];
            }
        }
        return new String[0];
    }

    public String getCacheCandidate(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        if (i == 0) {
            return JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), NetworkCacheInfo.KEY_CANDIDATE, "");
        }
        return 1 == i ? JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), NetworkCacheInfo.KEY_CANDIDATE, "") : "";
    }

    public Set<String> getCandidateHost() {
        return getInstance().getCandidateHost(getInstance().getCacheCandidates(NetworkHelper.getNetworkType(this.mAppContext)));
    }

    private Set<String> getCandidateHost(String[] strArr) {
        if (strArr == null) {
            return null;
        }
        HashSet hashSet = new HashSet();
        for (String str : strArr) {
            String hostFromUrl = getHostFromUrl(str);
            if (!TextUtils.isEmpty(hostFromUrl)) {
                hashSet.add(hostFromUrl);
            }
        }
        return hashSet;
    }

    public boolean checkCacheValid(int i) {
        String cacheNetworkInfo = getCacheNetworkInfo();
        Log.info(TAG, "Current Cache Info:" + cacheNetworkInfo);
        if (TextUtils.isEmpty(cacheNetworkInfo)) {
            return false;
        }
        String string = i == 0 ? JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_MOBILE), "Time", "") : "";
        if (1 == i) {
            string = JsonUtils.getString(JsonUtils.getJSONObject(cacheNetworkInfo, NetworkCacheInfo.KEY_WIFI), "Time", "");
        }
        try {
            if (TextUtils.isEmpty(string)) {
                return false;
            }
            return Long.parseLong(string) + 86400000 > System.currentTimeMillis();
        } catch (Exception e) {
            Log.error(TAG, "check cache valid error, ", e);
            return false;
        }
    }

    public boolean checkNetworkChanged() {
        if (isAppContextValid()) {
            int networkType = NetworkHelper.getNetworkType(this.mAppContext);
            String cacheNetworkInfo = getCacheNetworkInfo(networkType);
            if (TextUtils.isEmpty(cacheNetworkInfo)) {
                return true;
            }
            return !TextUtils.equals(NetworkHelper.getNetworkCheckInfo(this.mAppContext, networkType), cacheNetworkInfo);
        }
        return true;
    }

    public NetworkBean buildNetworkInformation() {
        if (isAppContextValid()) {
            int networkType = NetworkHelper.getNetworkType(this.mAppContext);
            return new NetworkBean(networkType, NetworkHelper.getNetworkCheckInfo(this.mAppContext, networkType));
        }
        return null;
    }

    public boolean isNeedSelectLine(String str) {
        if (TextUtils.isEmpty(str) || !isAppContextValid()) {
            return true;
        }
        NetworkMonitor networkMonitor = getInstance();
        if (!networkMonitor.checkCacheValid(NetworkHelper.getNetworkType(this.mAppContext))) {
            Log.warn(TAG, "Cache Line is invalid, need reselect line.");
            return true;
        }
        String hostFromUrl = getHostFromUrl(str);
        int portFromUrl = getPortFromUrl(str);
        if (portFromUrl != -1) {
            hostFromUrl = String.format(Locale.getDefault(), "%s:%s", hostFromUrl, Integer.valueOf(portFromUrl));
        }
        String cacheHostInfo = networkMonitor.getCacheHostInfo();
        if (!TextUtils.equals(hostFromUrl, cacheHostInfo)) {
            Log.warn(TAG, "VPN host is different, need reselect line." + hostFromUrl + "  " + cacheHostInfo);
            return true;
        }
        return networkMonitor.checkNetworkChanged();
    }

    private String getHostFromUrl(String str) {
        if (!str.startsWith("http://") && !str.startsWith("https://")) {
            str = String.format(Locale.getDefault(), "%s%s", "http://", str);
        }
        try {
            return new URL(str).getHost();
        } catch (MalformedURLException e) {
            Log.error(TAG, "Get host from url fail.", e);
            return "";
        }
    }

    private int getPortFromUrl(String str) {
        int port;
        int i = -1;
        if (TextUtils.isEmpty(str)) {
            return -1;
        }
        try {
            port = new URL((str.startsWith("http://") || str.startsWith("https://")) ? str : String.format(Locale.getDefault(), "%s%s", "http://", str)).getPort();
            try {
                Log.info(TAG, "From select url, port:" + port);
            } catch (MalformedURLException e) {
                e = e;
                i = port;
                Log.error(TAG, "Get host from url fail.", e);
                return i;
            }
        } catch (MalformedURLException e2) {
            e = e2;
        }
        if (port == -1) {
            i = str.startsWith("http://") ? 80 : port;
            if (str.startsWith("https://")) {
                return IGeneral.DEFAULT_SSL_PORT;
            }
            return i;
        }
        return port;
    }

    private static NetworkCacheInfo fromJson(String str) {
        NetworkCacheInfo networkCacheInfo = new NetworkCacheInfo();
        if (TextUtils.isEmpty(str)) {
            networkCacheInfo.setHost("").setWifiInfo(new NetworkCacheInfo.InfoBlock()).setMobileInfo(new NetworkCacheInfo.InfoBlock());
            return networkCacheInfo;
        }
        String string = JsonUtils.getString(str, NetworkCacheInfo.KEY_HOST, "");
        JSONObject jSONObject = JsonUtils.getJSONObject(str, NetworkCacheInfo.KEY_WIFI);
        String string2 = JsonUtils.getString(jSONObject, NetworkCacheInfo.KEY_INFO, "");
        NetworkCacheInfo.InfoBlock infoBlock = new NetworkCacheInfo.InfoBlock(JsonUtils.getString(jSONObject, "Line", ""), string2, JsonUtils.getString(jSONObject, NetworkCacheInfo.KEY_CANDIDATE, ""), JsonUtils.getString(jSONObject, "Time", ""));
        JSONObject jSONObject2 = JsonUtils.getJSONObject(str, NetworkCacheInfo.KEY_MOBILE);
        String string3 = JsonUtils.getString(jSONObject2, NetworkCacheInfo.KEY_INFO, "");
        networkCacheInfo.setHost(string).setWifiInfo(infoBlock).setMobileInfo(new NetworkCacheInfo.InfoBlock(JsonUtils.getString(jSONObject2, "Line", ""), string3, JsonUtils.getString(jSONObject2, NetworkCacheInfo.KEY_CANDIDATE, ""), JsonUtils.getString(jSONObject2, "Time", "")));
        return networkCacheInfo;
    }

    private static String toJson(NetworkCacheInfo networkCacheInfo) {
        if (networkCacheInfo == null) {
            Log.error(TAG, "Network Cache info is null!");
            return null;
        }
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put(NetworkCacheInfo.KEY_HOST, networkCacheInfo.getHost());
            JSONObject jSONObject2 = new JSONObject();
            jSONObject2.put("Line", networkCacheInfo.getWifiInfo().line);
            jSONObject2.put(NetworkCacheInfo.KEY_INFO, networkCacheInfo.getWifiInfo().networkInfo);
            jSONObject2.put("Time", networkCacheInfo.getWifiInfo().time);
            jSONObject2.put(NetworkCacheInfo.KEY_CANDIDATE, networkCacheInfo.getWifiInfo().candidate);
            jSONObject.put(NetworkCacheInfo.KEY_WIFI, jSONObject2);
            JSONObject jSONObject3 = new JSONObject();
            jSONObject3.put("Line", networkCacheInfo.getMobileInfo().line);
            jSONObject3.put(NetworkCacheInfo.KEY_INFO, networkCacheInfo.getMobileInfo().networkInfo);
            jSONObject3.put("Time", networkCacheInfo.getMobileInfo().time);
            jSONObject3.put(NetworkCacheInfo.KEY_CANDIDATE, networkCacheInfo.getMobileInfo().candidate);
            jSONObject.put(NetworkCacheInfo.KEY_MOBILE, jSONObject3);
            return jSONObject.toString();
        } catch (JSONException e) {
            Log.error(TAG, "Error:", e);
            return null;
        }
    }

    private void putStringValue(String str, String str2) {
        if (isAppContextValid()) {
            SharedPreferences.Editor edit = this.mAppContext.getSharedPreferences(PREFERENCE_NAME, 0).edit();
            edit.putString(str, str2);
            edit.commit();
        }
    }

    private String getStringValue(String str) {
        return !isAppContextValid() ? "" : this.mAppContext.getSharedPreferences(PREFERENCE_NAME, 0).getString(str, "");
    }

    public void clearSelectLineCache() {
        SharedPreferences sharedPreferences = this.mAppContext.getSharedPreferences(PREFERENCE_NAME, 0);
        if (sharedPreferences != null) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.clear();
            edit.apply();
            Log.info(TAG, "Clear Select Line Cache.");
        }
    }
}
